<template>
  <el-container class="product-detail-container">
    <el-main>
      <el-card v-if="loading" class="loading-card">
        <div class="loading-spinner">
          <el-progress :percentage="50" :indeterminate="true" />
          <p>加载商品详情中...</p>
        </div>
      </el-card>
      <el-card v-else-if="error" class="error-card">
        <el-alert :title="error" type="error" show-icon :closable="false" />
        <div style="margin-top: 20px; text-align: center;">
          <el-button @click="goBack">返回上一页</el-button>
          <el-button type="primary" @click="goToHome">返回首页</el-button>
        </div>
      </el-card>
      <el-card v-else-if="product" class="product-card-detail">
        <el-row :gutter="30">
          <!-- 商品图片区 -->
          <el-col :md="10">
            <el-carousel 
              v-if="product.images && product.images.length > 0"
              trigger="click" 
              height="400px" 
              arrow="always"
              indicator-position="outside"
            >
              <el-carousel-item v-for="image in product.images" :key="image.id">
                <img :src="image.image_url" :alt="image.alt_text || product.name" class="main-product-image"/>
              </el-carousel-item>
            </el-carousel>
            <img 
              v-else-if="product.thumbnail_url"
              :src="product.thumbnail_url" 
              :alt="product.name" 
              class="main-product-image"
            />
            <img 
              v-else
              src="https://via.placeholder.com/400x400.png?text=No+Image" 
              alt="No image available" 
              class="main-product-image"
            />
          </el-col>

          <!-- 商品信息与操作区 -->
          <el-col :md="14">
            <h1>{{ product.name }}</h1>
            <p class="short-description">{{ product.short_description }}</p>
            
            <div class="price-section">
              <span class="current-price">¥ {{ product.price }}</span>
              <span v-if="product.original_price && product.original_price > product.price" class="original-price">
                ¥ {{ product.original_price }}
              </span>
            </div>

            <el-divider />

            <el-form label-width="80px">
              <el-form-item label="分类">
                <router-link :to="{ name: 'Products', query: { category_slug: product.category_slug } }">
                  {{ product.category_name }}
                </router-link>
              </el-form-item>
              <el-form-item label="库存">
                <span>{{ product.stock_quantity > 0 ? `剩余 ${product.stock_quantity} 件` : '暂无库存' }}</span>
              </el-form-item>
              <el-form-item label="数量" v-if="product.stock_quantity > 0">
                <el-input-number v-model="quantity" :min="1" :max="product.stock_quantity" />
              </el-form-item>
            </el-form>

            <div class="actions">
              <el-button 
                type="warning" 
                size="large" 
                @click="handleAddToCart" 
                :disabled="product.stock_quantity === 0 || quantity > product.stock_quantity"
              >
                <el-icon><ShoppingCart /></el-icon> 添加到购物车
              </el-button>
              <!-- 可以添加立即购买按钮 -->
            </div>
          </el-col>
        </el-row>

        <!-- 商品描述 -->
        <el-tabs v-model="activeTab" class="description-tabs">
          <el-tab-pane label="商品详情" name="description">
            <div v-if="product.description" v-html="product.description"></div>
            <el-empty v-else description="暂无详细描述"></el-empty>
          </el-tab-pane>
          <el-tab-pane label="规格参数" name="specifications">
            <!-- 假设规格参数在 product.specifications (JSON对象) -->
            <div v-if="product.specifications">
              <el-descriptions border :column="1">
                <el-descriptions-item 
                  v-for="(value, key) in product.specifications" 
                  :key="key" 
                  :label="key.toString()"
                >
                  {{ value.toString() }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
            <el-empty v-else description="暂无规格参数"></el-empty>
          </el-tab-pane>
          <!-- 可以添加评论区域 -->
        </el-tabs>

      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import productService from '../api/product.service';
import cartService from '../api/cart.service';
import { ElMessage } from 'element-plus';
// ShoppingCart 图标已全局注册

const route = useRoute();
const router = useRouter();

const product = ref(null);
const loading = ref(true);
const error = ref(null);
const quantity = ref(1);
const activeTab = ref('description');

const fetchProductDetail = async (slug) => {
  loading.value = true;
  error.value = null;
  product.value = null;
  try {
    const response = await productService.getProduct(slug);
    product.value = response.data; 
    // 重置购买数量为1，以防用户在不同商品间切换
    quantity.value = 1; 
  } catch (err) {
    console.error('获取商品详情失败:', err);
    if (err.status === 404) {
        error.value = '抱歉，您要找的商品不存在。';
    } else {
        error.value = err.message || '获取商品详情失败，请稍后再试。';
    }
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
};

const handleAddToCart = async () => {
  if (!product.value) return;
  try {
    await cartService.addItem({ product_id: product.value.id, quantity: quantity.value });
    ElMessage.success(`${product.value.name} (数量: ${quantity.value}) 已添加到购物车`);
  } catch (err) {
    console.error('添加到购物车失败:', err);
    const errorMessage = err.message || '添加到购物车失败';
    ElMessage.error(errorMessage);
  }
};

const goBack = () => {
  router.go(-1);
};

const goToHome = () => {
  router.push({ name: 'Home' });
};

// 监听路由参数变化，例如从一个商品详情页跳转到另一个
watch(() => route.params.slug, (newSlug) => {
  if (newSlug) {
    fetchProductDetail(newSlug);
  }
});

onMounted(() => {
  if (route.params.slug) {
    fetchProductDetail(route.params.slug);
  }
});

</script>

<style scoped>
.product-detail-container {
  padding: 20px;
  background-color: #f5f5f5;
}

.loading-card,
.error-card {
  padding: 40px;
  text-align: center;
}

.product-card-detail {
  padding: 20px;
}

.main-product-image {
  width: 100%;
  height: 400px;
  object-fit: contain; /* 改为contain以显示完整图片，或cover填充 */
  border-radius: 4px;
  background-color: #fff; /* 图片背景，以防透明图片 */
}

.el-carousel__item img {
  display: block;
  margin: 0 auto;
}

.short-description {
  color: #666;
  margin: 10px 0 20px;
  font-size: 14px;
}

.price-section {
  margin-bottom: 20px;
}

.current-price {
  font-size: 24px;
  color: #ff4d4f;
  font-weight: bold;
  margin-right: 10px;
}

.original-price {
  font-size: 16px;
  color: #999;
  text-decoration: line-through;
}

.actions {
  margin-top: 30px;
}

.description-tabs {
  margin-top: 40px;
}

/* 如果 v-html 包含的 HTML 有特定样式需求，可以在这里添加 */
/* 例如：:deep(img) { max-width: 100%; height: auto; } */
</style> 